<?php

namespace app\backend\service;

use app\common\model\CategoryModel;
use app\common\model\FeedbackModel;
use app\common\model\MemberModel;
use app\common\model\SourceModel;
use app\common\RootService;
use app\common\validate\CategoryValidate;

class FeedbackService extends RootService
{
    /**
     * 资源标签
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function feedbackLabel()
    {
        return ['stateLabel' => FeedbackModel::$stateLabel, 'bindType' => MemberModel::$bindType,
            'auditNames' => AdminService::adminNames(0, true)];
    }

    /**
     * 栏目列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function lists(array $params)
    {
        // 资源标签
        $feedbackLabel = $this->feedbackLabel();
        // 数据源
        $feedbackList = $this->page($this->feedbackModel($params)->order(['fd.state' => 'asc', 'fd.id' => 'desc']));
        // 数据处理
        array_walk($feedbackList['data'], function (&$row) use ($feedbackLabel) {
            empty($row['email']) && $row['email'] = '--';
            empty($row['audit_time']) && $row['audit_time'] = '--';
            empty($row['create_time']) && $row['create_time'] = '--';
            $row['bindType'] = $feedbackLabel['bindType'][$row['bind_type']] ?? '';
            $row['realName'] = $feedbackLabel['auditNames'][$row['audit_id']] ?? '--';
            $row['stateLabel'] = $feedbackLabel['stateLabel'][$row['state']] ?? $feedbackLabel['stateLabel'][1];
        });
        return $feedbackList;
    }

    /**
     * 回复反馈
     * @param array $params
     * @return string[]
     * @throws \app\common\RootException
     */
    public function edit(array $params)
    {
        // 参数校验
        empty($params['reply']) && $this->errorException('请输入回复内容');
        // 数据处理
        $renewData = ['id' => $params['id'], 'reply' => trim($params['reply']), 'audit_id' => adminInfo('id'),
            'state' => 1, 'audit_time' => date('Y-m-d H:i:s')];
        // 回复失败
        FeedbackModel::update($renewData) || $this->errorException('回复失败');
        // 添加成功
        return ['msg' => '回复成功', 'preload' => true];
    }

    /**
     * 数据校验
     * @param array $taskData
     * @param string $scene
     * @throws \app\common\RootException
     */
    protected function verify(array $taskData, string $scene)
    {
        $validate = new CategoryValidate();
        // 参数校验
        $this->validate($validate, $scene);
        // 栏目标签
        $sourceDomain = SourceModel::where(['state' => 0])->column('domain', 'id');
        // 采集任务校验
        empty($params['type']) && array_walk($taskData, function ($row) use ($validate, $sourceDomain) {
            $line = "采集任务第【{$row['row']}】行";
            $validate->scene('taskData')->check($row) || $this->errorException($line . $validate->getError());
            isset($sourceDomain[$row['sourceId']]) || $this->errorException($line . '数据来源无效');
            strpos($row['url'], $sourceDomain[$row['sourceId']]) == false && $this->errorException($line . '采集地址和数据来源不匹配');
        });
    }


    /**
     * 栏目详情
     * @param int $feedbackId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(int $feedbackId)
    {
        return FeedbackModel::where(['id' => $feedbackId])->find()->toArray();
    }

    /**
     * 快速处理
     * @param int $feedbackId
     * @return array
     */
    public function handleWith(int $feedbackId)
    {
        $renewData = ['state' => 3, 'audit_id' => adminInfo('id')];
        FeedbackModel::where(['id' => $feedbackId])->update($renewData) || $this->errorException('处理失败');
        return ['msg' => '处理成功', 'reload' => true];
    }

    /**
     * 反馈列表模型
     * @param array $params
     * @return CategoryModel
     */
    protected function feedbackModel(array $params)
    {
        // 用户ID筛选
        empty($params['invite']) || $where[] = ['m.invite', '=', $params['invite']];
        // 用户筛选
        empty($params['memberId']) || $where[] = ['fd.member_id', '=', $params['memberId']];
        // 反馈日期筛选
        empty($params['date']) || $where[] = ['fd.create_time', 'between', betweenDate($params['date'])];
        // 反馈状态筛选
        strpos($params['state'] ?? '', '1') !== false && $params['state'] .= ',2';
        condition($params['state'] ?? '') && $where[] = ['fd.state', 'in', explode(',', $params['state'])];
        // 回复人筛选
        condition($params['auditId'] ?? '') && $where[] = ['fd.audit_id', 'in', explode(',', $params['auditId'])];
        // 筛选字段
        $fields = ['fd.id fid', 'fd.audit_id', 'fd.content', 'fd.reply', 'fd.icon', 'fd.email fdEmail', 'fd.audit_time',
            'fd.state', 'fd.create_time', 'm.account', 'm.nickname', 'm.avatar', 'm.bind_type', 'm.invite', 'm.id',
            'm.bind_type', 'm.email', 'm.state memberState'];
        // 筛选结果
        return FeedbackModel::alias('fd')->join(['sys_member' => 'm'], 'fd.member_id = m.id', 'left')
            ->where($where ?? [])->field($fields);
    }
}